// miniprogram/devTools/device/device.js
// https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth-peripheral/wx.onBLEPeripheralConnectionStateChanged.html
Page({

  data: {
    funcList: [{
      title: '振动能力',
      funcs: [{
        name: '短时间的振动',
        method: 'vibrateFunc',
        params: 'short'
      }, {
        name: '长时间的振动',
        method: 'vibrateFunc',
        params: 'long'
      }, {
        name: '持续的振动',
        method: 'vibrateFunc',
        params: 'continue'
      }]
    }, {
      title: '扫码能力',
      funcs: [{
        name: '客户端扫码',
        method: 'scanCode'
      }],
      content: ''
    }, {
      title: '陀螺仪能力',
      funcs: [{
        name: '开始监听陀螺仪',
        method: 'gyroscopeFunc',
        params: 'start'
      }, {
        name: '停止监听陀螺仪',
        method: 'gyroscopeFunc',
        params: 'stop'
      }],
      content: ''
    }, {
      title: '设备方向能力',
      funcs: [{
        name: '开始监听设备方向',
        method: 'deviceMotionFunc',
        params: 'start'
      }, {
        name: '停止监听设备方向',
        method: 'deviceMotionFunc',
        params: 'stop'
      }],
      content: ''
    }, {
      title: '罗盘能力',
      funcs: [{
        name: '开始监听罗盘数据',
        method: 'compassFunc',
        params: 'start'
      }, {
        name: '停止监听罗盘数据',
        method: 'compassFunc',
        params: 'stop'
      }],
      content: ''
    }, {
      title: '加速度',
      funcs: [{
        name: '开始监听加速度',
        method: 'accelerometerFunc',
        params: 'start'
      }, {
        name: '停止监听加速度',
        method: 'accelerometerFunc',
        params: 'stop'
      }],
      content: ''
    }, {
      title: '电话功能',
      funcs: [{
        name: '拨打电话',
        method: 'mobileFunc',
        params: 'call'
      }, {
        name: '添加通讯录联系人',
        method: 'mobileFunc',
        params: 'add'
      }],
      content: ''
    }, {
      title: '屏幕功能',
      funcs: [{
        name: '设置屏幕亮度',
        method: 'screenFunc',
        params: 'setBrightness'
      }, {
        name: '获取屏幕亮度',
        method: 'screenFunc',
        params: 'getBrightness'
      }, {
        name: '保持常亮',
        method: 'screenFunc',
        params: 'keepOn'
      }, {
        name: '关闭常亮',
        method: 'screenFunc',
        params: 'keepOff'
      }, {
        name: '监听用户截屏事件',
        method: 'screenFunc',
        params: 'captureScreenOn'
      }, {
        name: '取消监听用户截屏事件',
        method: 'screenFunc',
        params: 'captureScreenOff'
      }],
      content: ''
    }, {
      title: '网络功能',
      funcs: [{
        name: '监听网络状态',
        method: 'networkFunc',
        params: 'onStatusChange'
      }, {
        name: '取消监听网络状态',
        method: 'networkFunc',
        params: 'offStatusChange'
      }, {
        name: '获取网络类型',
        method: 'networkFunc',
        params: 'getType'
      }],
      content: ''
    }, {
      title: '剪贴板功能',
      funcs: [{
        name: '设置剪贴板的内容',
        method: 'clipboardFunc',
        params: 'setClipboard'
      }, {
        name: '获取剪贴板的内容',
        method: 'clipboardFunc',
        params: 'getClipboard'
      }],
      content: ''
    }, {
      title: '电量功能',
      funcs: [{
        name: '获取设备电量',
        method: 'batteryFunc'
      }],
      content: ''
    }, {
      title: '蓝牙功能',
      funcs: [{
        name: '1.开启蓝牙',
        method: 'bluetoothFunc',
        params: 'startBluetooth'
      }, {
        name: '关闭蓝牙',
        method: 'bluetoothFunc',
        params: 'closeBluetooth'
      }, {
        name: '2.开始搜寻蓝牙设备',
        method: 'bluetoothFunc',
        params: 'discoveryOn'
      }, {
        name: '取消搜寻蓝牙设备',
        method: 'bluetoothFunc',
        params: 'discoveryOff'
      }, {
        name: '02.已连接状态的设备',
        method: 'bluetoothFunc',
        params: 'connectedDevices'
      }, {
        name: '3.所有已发现的蓝牙设备',
        method: 'bluetoothFunc',
        params: 'getDevices'
      }, {
        name: '02.获取蓝牙适配器状态',
        method: 'bluetoothFunc',
        params: 'getState'
      }, ],
      content: ''
    }, {
      title: 'Wifi功能',
      funcs: [{
        name: '1.开启WiFi',
        method: 'wifiFunc',
        params: 'startWifi'
      }, {
        name: '关闭WiFi',
        method: 'wifiFunc',
        params: 'closeWifi'
      }, {
        name: '2.获取Wifi列表',
        method: 'wifiFunc',
        params: 'getWifiList'
      }, {
        name: '2.获取连接的Wifi信息',
        method: 'wifiFunc',
        params: 'getConnectWifi'
      }, {
        name: '3.连接Wifi',
        method: 'wifiFunc',
        params: 'connectWifiOn'
      }, {
        name: '4.取消连接Wifi',
        method: 'wifiFunc',
        params: 'connectWifiOff'
      }],
      content: ''
    }, {
      title: 'NFC功能',
      funcs: [{
        name: '1.开启NFC',
        method: 'nfcFunc',
        params: 'startNfc'
      }],
      content: ''
    }],
    permission: false,
    showInputDialog: false,
    inputObj: {}
  },
  onLoad: function (options) {

  },
  onShow() {
    if (this.data.permission)
      this.getLocationPermission()
  },
  onShareAppMessage: function () {

  },
  nfcFunc(event) {
    wx.showToast({
      title: '暂未实现',
      icon: 'none'
    })
  },
  // Wifi功能
  wifiFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('Wifi功能')
    let func = this.getResultFunc('Wifi功能')
    switch (params) {
      case "startWifi":
        wx.startWifi(result)
        wx.onGetWifiList(func)
        break
      case "closeWifi":
        wx.stopWifi(result)
        wx.offGetWifiList(func)
        break
      case "getWifiList":
        wx.authorize({
          scope: 'scope.userLocation',
          success: res => {
            wx.getWifiList(result)
          },
          fail: err => {
            this.setData({
              permission: true
            })
            this.modifyContent('Wifi功能', JSON.stringify(err), true)
          }
        })
        break
      case "getConnectWifi":
        wx.getConnectedWifi(result)
        break
      case "connectWifiOn":
        this.connectWifiInputPsd()
        break
      case "connectWifiOff":
        wx.offWifiConnected(func)
        break;
      case "connectWifiValue": //使用密码连接
        result.SSID = event.SSID
        result.password = event.password
        wx.connectWifi(result)
        wx.onWifiConnected(func)
        break
    }
  },
  // 连接wifi输入密码逻辑
  connectWifiInputPsd() {
    let contentObj = this.getContent('Wifi功能')
    if (!contentObj.wifiList) {
      wx.showToast({
        title: '请先获取wifi列表',
        icon: 'none'
      })
    } else {
      let list = []
      let wifiList = contentObj.wifiList
      // console.log(wifiList)
      // 按照信号强度从大到小排序
      wifiList.sort((a, b) => {
        return b.signalStrength - a.signalStrength
      })
      console.log(wifiList)
      for (var wifi of wifiList) {
        // console.log("for", wifi)
        if (list.length < 6 && wifi.SSID)
          list.push(wifi.SSID)
      }
      console.log(list)
      wx.showActionSheet({
        itemList: list,
        success: res => {
          let tapIndex = res.tapIndex
          let inputObj = {
            SSID: list[tapIndex]
          }
          this.setData({
            inputObj,
            showInputDialog: true
          })
        }
      })
    }
  },
  // 蓝牙功能
  bluetoothFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('蓝牙功能')
    let func = this.getResultFunc('蓝牙功能')
    switch (params) {
      case "startBluetooth":
        wx.openBluetoothAdapter(result)
        wx.onBluetoothAdapterStateChange(func)
        break
      case "closeBluetooth":
        wx.closeBluetoothAdapter(result)
        wx.offBluetoothAdapterStateChange(func)
        break
      case "discoveryOn":
        wx.startBluetoothDevicesDiscovery(result)
        wx.onBluetoothDeviceFound(func);
        break
      case "discoveryOff":
        wx.stopBluetoothDevicesDiscovery(result)
        wx.offBluetoothDeviceFound(func)
        break
      case "connectedDevices":
        wx.getConnectedBluetoothDevices(result)
        break
      case "getDevices":
        wx.getBluetoothDevices(result)
        break
      case "getState":
        wx.getBluetoothAdapterState(result)
        break
    }
  },
  // 电量功能
  batteryFunc() {
    let result = this.getResultObj('电量功能')
    wx.getBatteryInfoSync(result)
  },
  // 剪贴板功能
  clipboardFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('剪贴板功能')
    let func = this.getResultFunc('剪贴板功能')
    switch (params) {
      case "setClipboard":
        result.data = "测试"
        wx.setClipboardData(result)
        break
      case "getClipboard":
        wx.getClipboardData(result)
        break
    }
  },
  // 网络功能
  networkFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('网络功能')
    let func = this.getResultFunc('网络功能')
    switch (params) {
      case "onStatusChange":
        wx.onNetworkStatusChange(func)
        break
      case "offStatusChange":
        wx.offNetworkStatusChange(func)
        break
      case "getType":
        wx.getNetworkType(result)
        break
    }
  },
  // 屏幕功能
  screenFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('屏幕功能')
    let func = this.getResultFunc('屏幕功能')
    switch (params) {
      case "setBrightness":
        result.value = 0.5
        wx.setScreenBrightness(result)
        break
      case "getBrightness":
        wx.getScreenBrightness(result)
        break
      case "keepOn":
        result.keepScreenOn = true
        wx.setKeepScreenOn(result)
        break
      case "keepOff":
        result.keepScreenOn = false
        wx.setKeepScreenOn(result)
        break
      case "captureScreenOn":
        wx.onUserCaptureScreen(func)
        break
      case "captureScreenOff":
        wx.offUserCaptureScreen(func)
        break
    }
  },
  // 电话功能
  mobileFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('电话功能')
    switch (params) {
      case "call":
        result.phoneNumber = '10086'
        wx.makePhoneCall(result)
        break
      case "add":
        result.firstName = '测试'
        wx.addPhoneContact(result)
        break
    }
  },
  // 加速度
  accelerometerFunc() {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('加速度')
    let func = this.getResultFunc('加速度')
    switch (params) {
      case "start":
        wx.startAccelerometer(result)
        wx.onAccelerometerChange(func)
        break
      case "stop":
        wx.stopAccelerometer(result)
        wx.offAccelerometerChange()
        break
    }
  },
  // 罗盘
  compassFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('罗盘能力')
    let func = this.getResultFunc('罗盘能力')
    switch (params) {
      case "start":
        wx.startCompass(result)
        wx.onCompassChange(func)
        break
      case "stop":
        wx.stopCompass(result)
        wx.offCompassChange()
        break
    }
  },
  // 设备方向
  deviceMotionFunc(event) {
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('设备方向能力')
    let func = this.getResultFunc('设备方向能力')
    switch (params) {
      case "start":
        wx.startDeviceMotionListening(result)
        wx.onDeviceMotionChange(func)
        break
      case "stop":
        wx.stopDeviceMotionListening(result)
        wx.offDeviceMotionChange()
        break
    }
  },
  // 陀螺仪
  gyroscopeFunc(event) {
    // console.log(event)
    let params = event.currentTarget.dataset.params
    let result = this.getResultObj('陀螺仪能力')
    let func = this.getResultFunc('陀螺仪能力')
    switch (params) {
      case "start":
        wx.startGyroscope(result)
        wx.onGyroscopeChange(func)
        break
      case "stop":
        wx.stopGyroscope(result)
        wx.offGyroscopeChange()
        break
    }
  },
  // 振动
  vibrateFunc(event) {
    console.log(event)
    let params = event.currentTarget.dataset.params
    let result = {
      success: res => {
        console.log(res)
      }
    }
    switch (params) {
      case "short":
        wx.vibrateShort(result)
        break
      case "long":
        wx.vibrateLong(result)
        break
      case "continue":
        let continueV = setInterval(() => {
          wx.vibrateShort(result)
        }, 100);
        setTimeout(() => {
          clearInterval(continueV)
        }, 6 * 1000)
        break
    }
  },
  scanCode(event) {
    let result = {
      success: res => {
        this.modifyContent('扫码能力', JSON.stringify(res))
      }
    }
    wx.scanCode(result)
  },
  // 获取返回结果方法
  getResultFunc(title) {
    let func = res => {
      this.modifyContent(title, JSON.stringify(res))
    }
    return func
  },
  // 获取返回结果对象
  getResultObj(title) {
    let result = {
      success: res => {
        console.log(res)
        this.modifyContent(title, JSON.stringify(res))
      },
      fail: err => {
        this.modifyContent(title, JSON.stringify(err))
      }
    }
    return result
  },
  // 清除文本内容
  clearContent(event) {
    console.log(event)
    let title = event.currentTarget.dataset.title
    this.modifyContent(title, '')
  },
  // 获取文本内容
  getContent(title) {
    let content = '{}'
    let funcList = this.data.funcList
    funcList.forEach(funcObj => {
      if (funcObj.title == title && funcObj.content) content = funcObj.content
    })
    return JSON.parse(content)
  },
  // 修改文本内容
  modifyContent(title, content, openSetting) {
    let funcList = this.data.funcList
    funcList.forEach(funcObj => {
      if (funcObj.title == title) {
        funcObj.content = content
        funcObj.openSetting = openSetting
      }
    })
    this.setData({
      funcList
    })
  },
  getLocationPermission() {
    wx.authorize({
      scope: 'scope.userLocation',
      success: res => {
        this.modifyContent('Wifi功能', JSON.stringify(res), false)
      },
      fail: err => {
        this.modifyContent('Wifi功能', JSON.stringify(err), true)
      }
    })
  },
  inputBtnClick(event) {
    console.log(event)
    let inputObj = event.detail
    this.setData({
      showInputDialog: false
    })
    if (inputObj.key == 1) {
      let event = {
        currentTarget: {
          dataset: {
            params: 'connectWifiValue'
          }
        },
        // SSID: this.data.inputObj.SSID,
        SSID: '智慧旅游',
        password: inputObj.value
      }
      this.wifiFunc(event)
    }
  }
})